﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;

namespace Microsoft.Samples.Kinect.BodyBasics.Controls
{
    /// <summary>
    /// SerialPort.xaml 的交互逻辑
    /// </summary>
    public partial class SerialPort : UserControl
    {
        public SerialPort()
        {
            InitializeComponent();
            Init_serialPort();
        }

        private Comm comm;

        //private Queue<Package> sendQueue;

        

        private void Init_serialPort()
        {
            comm = new Comm();
            //List<Comm> list = new List<Comm>();
            //初始化下拉框
            string[] comms = System.IO.Ports.SerialPort.GetPortNames();
            foreach(string s in comms)
            {
                cbb_comms.Items.Add(s);
            }
            if (cbb_comms.Items.Count > 0)
            {
                cbb_comms.SelectedIndex = cbb_comms.Items.Count - 1;
            }

        }

        private void btn_open_Click(object sender, RoutedEventArgs e)
        {
            string content = btn_open.Content.ToString();
            if (content == "open")
            {
                try
                {
                    Console.WriteLine("COM: " + comm.Name);
                    Console.WriteLine("selected: " + cbb_comms.SelectedItem.ToString());
                    comm.Name = cbb_comms.SelectedItem.ToString();

                    comm.serialPort.BaudRate = int.Parse(cbb_baudRate.SelectedItem.ToString());
                    comm.serialPort.DataBits = int.Parse(cbb_dataBits.SelectedItem.ToString());
                    comm.serialPort.StopBits = (System.IO.Ports.StopBits)cbb_stopBits.SelectedItem;
                    comm.serialPort.Parity = (System.IO.Ports.Parity)cbb_parity.SelectedItem;
                    comm.DataReceived += Comm_DataReceived;
                    comm.Open();
                    btn_open.Content = "close";
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void Comm_DataReceived(byte[] readBuffer)
        {

            Console.Write("datareceived:");
            foreach(byte b in readBuffer)
            {
                Console.Write(b.ToString("x"));
            }
        }

        public void AddPackage(Package package)
        {
            comm.AddPackge(package);
        }
    }
}
